<?php

namespace App\Http\Controllers\Callback;

use App\Facades\EasyWechat;
use App\Http\Controllers\Controller;
use App\Models\WxMpList;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\App;
use \EasyWeChat\Kernel\Messages\Message;


/**
 * 微信服务号回调入口控制器
 * @package App\Http\Controllers\Wechat
 */
class WechatController extends Controller
{
    /**
     * 处理微信的请求消息
     * @return string
     */
    public function serve($appid)
    {
        Log::error('request arrived.');
        //注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        try {
            $app = EasyWechat::officialAccount($appid);
            //文本消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\TextMessageHandler($appid))->handle($message);
            }, Message::TEXT);
            //图片消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\ImageMessageHandler($appid))->handle($message);
            }, Message::IMAGE);
            //音频消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\VoiceMessageHandler($appid))->handle($message);
            }, Message::VOICE);
            //视频消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\VideoMessageHandler($appid))->handle($message);
            }, Message::VIDEO);
            //小视频消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\ShortVideoMessageHandler($appid))->handle($message);
            }, Message::SHORT_VIDEO);
            //地理位置消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\LocationMessageHandler($appid))->handle($message);
            }, Message::LOCATION);
            //链接消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\LinkMessageHandler($appid))->handle($message);
            }, Message::LINK);
            //事件消息
            $app->server->push(function ($message) use($appid) {
                return (new \App\Services\WechatHandler\EventMessageHandler($appid))->handle($message);
            }, Message::EVENT);

            $response = $app->server->serve();
            //触发微信发送消息事件
            \App\Jobs\WxmsgSendHandle::dispatch($appid, $response->getContent())->onQueue('low');
            //将响应输出
            $response->send();
        } catch (\Exception $e) {
            Log::info($e->getMessage());
            //生产环境不报错
            if (App::environment('product')) {
                echo 'success';
            } else {
                throw new \Exception($e->getMessage());
            }
        }
    }
    /**
     * 网页授权跳转（中转）方法
     */
    public function oauth(Request $request)
    {
        try {
            $appid = $request->get('appid', '');
            $url = $request->get('url', '');
            $scopes = $request->get('scopes', '');
            if (empty($appid)) {
                throw new \Exception('appid参数不能为空');
            }

            if (empty($url)) {
                throw new \Exception('url参数不能为空');
            }

            $app = WxMpList::where('appid', $appid)->first();

            if (! $app){
                throw new \Exception('appid不合法');
            }

            $scopes = (!empty($scopes) && in_array($scopes, $this->scope_arr)) ? $scopes : 'snsapi_base';

            $officialAccount = EasyWechat::officialAccount($appid);

            if ($request->has('code')) {
                $user = $officialAccount->oauth->user();
                $sufix = ((strpos($url, '?') !== false) ? '&' : '?');

                $url_arr = [
                    'appid' => $appid,
                    'openid' => $user->id
                ];

                if ($user->nickname){
                    $url_arr['nickname'] = $user->nickname;
                }

                if ($user->nickname){
                    $url_arr['avatar'] = $user->avatar;
                }

                $url_query = http_build_query($url_arr);

                $call_remote_url = $url . $sufix . $url_query;
                return redirect()->to($call_remote_url);
            }
            return $officialAccount->oauth->scopes([$scopes])->setRequest($request)->redirect($request->fullUrl());

        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }
}
